package com.hanbang.cxgz_2.view.about_me.activity;

import android.content.Intent;
import android.support.design.widget.TextInputLayout;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hanbang.audiorecorder.RecordActivity;
import com.hanbang.cxgz_2.R;
import com.hanbang.cxgz_2.appliction.MyApplication;
import com.hanbang.cxgz_2.appliction.base.baseadapter.ViewHolder;
import com.hanbang.cxgz_2.appliction.base.baseadapter.abslistview.CommonAdapter;
import com.hanbang.cxgz_2.appliction.base.view.activity.BaseMvpActivity;
import com.hanbang.cxgz_2.pressenter.about_me.IssuerClassroomPresenter;
import com.hanbang.cxgz_2.utils.http.GlideUtils;
import com.hanbang.cxgz_2.utils.other.EditHelper;
import com.hanbang.cxgz_2.utils.other.FileUtils;
import com.hanbang.cxgz_2.utils.other.MediaFile;
import com.hanbang.cxgz_2.utils.other.Validators;
import com.hanbang.cxgz_2.utils.ui.AndroidBug5497Workaround;
import com.hanbang.cxgz_2.utils.ui.SnackbarUtil;
import com.hanbang.cxgz_2.utils.ui.ToastUtils;
import com.hanbang.cxgz_2.utils.ui.UiUtils;
import com.hanbang.cxgz_2.view.about_me.iview.IssuerClassroomView;
import com.hanbang.cxgz_2.view.other.PhotoActivity;
import com.hanbang.cxgz_2.view.widget.AnimCheckBox;
import com.hanbang.cxgz_2.view.widget.GridViewForScrollView;
import com.hanbang.cxgz_2.view.widget.dialog.DialogDateTime;
import com.hanbang.cxgz_2.view.widget.dialog.DialogProgress;
import com.hanbang.cxgz_2.view.widget.dialog.DialogSelectMode;
import com.hanbang.cxgz_2.view.widget.media.MusicPlayView;
import com.hanbang.cxgz_2.view.widget.media.VideoPlayView;
import com.hanbang.videoplay.view.VideoCameraActivity;

import java.util.ArrayList;
import java.util.Calendar;

import butterknife.BindView;
import butterknife.OnClick;
import me.nereo.multi_image_selector.MultiImageSelector;
import me.nereo.multi_image_selector.MultiImageSelectorActivity;


/**
 * 作者　　: 杨阳
 * 创建时间: 2016/9/2 10:44
 * 邮箱　　：360621904@qq.com
 * <p>
 * 功能介绍：发布课堂
 */

public class IssuerClassroomActivity extends BaseMvpActivity<IssuerClassroomView, IssuerClassroomPresenter> implements IssuerClassroomView, AnimCheckBox.OnCheckedChangeListener {
    @BindView(R.id.find_uploading_k_activity_root)
    RelativeLayout viewRoot;

    @BindView(R.id.applyName)
    TextInputLayout applyName;

    @BindView(R.id.xianXiaKeTang)
    AnimCheckBox xianXiaKeTang;
    @BindView(R.id.zaiXiaKeTang)
    AnimCheckBox zaiXiaKeTang;

    @BindView(R.id.classroomName)
    TextInputLayout classroomName;
    @BindView(R.id.classroomBrief)
    TextInputLayout classroomBrief;
    @BindView(R.id.address)
    TextInputLayout address;
    @BindView(R.id.inputPrice)
    TextInputLayout inputPrice;
    @BindView(R.id.startTiem)
    TextView startTiem;
    @BindView(R.id.endTiem)
    TextView endTiem;
    @BindView(R.id.student)
    TextInputLayout student;
    //地址
    @BindView(R.id.ll_address)
    LinearLayout ll_address;

    //海报路径
    private String haiBaoPath;
    @BindView(R.id.haiBao)
    ImageView haiBao;
    //视频路径
    private String videoPlayPath;
    @BindView(R.id.find_uploading_k_activity_videoPlay)
    VideoPlayView videoPlay;
    //音频路径
    private String musicPlayPath;
    @BindView(R.id.music_play)
    MusicPlayView musicPlay;
    //显示过程图片
    @BindView(R.id.showProcessPicture)
    GridViewForScrollView showProcessPicture;
    private ArrayList<String> processPicturePhat = new ArrayList<>();

    private EditHelper editHelper = new EditHelper(this);


    @Override
    public int getContentView() {
        return R.layout.activity_uploading_classroom;
    }


    @Override
    public void clearData() {


    }

    @Override
    public IssuerClassroomPresenter initPressenter() {
        return new IssuerClassroomPresenter();
    }

    @Override
    public void initView() {
        AndroidBug5497Workaround androidBug5497Workaround = AndroidBug5497Workaround.assistActivity(this);
        viewRoot.setPadding(0, UiUtils.getStatusHeight(this) - 2, 0, 0);
        toolbar.setBack(this);
        toolbar.setTitle("上传开放式秘籍");

        processPicturePhat.add("");
        showProcessPicture.setAdapter(adapter);
        musicPlay.setVisibility(View.GONE);
        videoPlay.setVisibility(View.GONE);
        xianXiaKeTang.setOnCheckedChangeListener(this);
        zaiXiaKeTang.setOnCheckedChangeListener(this);

        editHelper.addEditHelperData(new EditHelper.EditHelperData(applyName, Validators.getLengthSRegex(1, 20), "请输入申请人名称"));
        editHelper.addEditHelperData(new EditHelper.EditHelperData(classroomName, Validators.getLengthSRegex(1, 20), "请输入课堂名称"));
        editHelper.addEditHelperData(new EditHelper.EditHelperData(classroomBrief, Validators.getLengthSRegex(1, 100), "请输入课堂简介"));
        editHelper.addEditHelperData(new EditHelper.EditHelperData(inputPrice, Validators.getLengthSRegex(1, 7), "请输入价格"));
        editHelper.addEditHelperData(new EditHelper.EditHelperData(student, Validators.getLengthSRegex(1, 4), "请输入招收学员数量"));

    }


    @Override
    public int getStatusBarPaddingTop() {
        return 0;
    }

    @Override
    public int getStatusBarResource() {
        return R.color.yellow_top;
    }

    @Override
    public void parseIntent(Intent intent) {

    }

    CommonAdapter adapter = new CommonAdapter<String>(this, R.layout.item_photo_select, processPicturePhat) {
        @Override
        public void convert(final ViewHolder holder, String item) {

            if (holder.getmPosition() == processPicturePhat.size() - 1) {
                holder.setVisible(R.id.item_photo_selectDelete, false);
                //因为有缓存所以增加延时加载
                holder.getView(R.id.item_photo_selectDelete).postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        holder.setImageResource(R.id.item_photo_selectImage, R.mipmap.my_release_ico_addpic);
                    }
                }, 100);


            } else if (!TextUtils.isEmpty(item)) {
                holder.setImageBitmap(R.id.item_photo_selectImage, item);
                holder.setVisible(R.id.item_photo_selectDelete, true);
            }

            holder.setOnClickListener(R.id.item_photo_selectImage, new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (processPicturePhat.size() - 1 == holder.getmPosition()) {

                        processPicturePhat.remove(processPicturePhat.size() - 1);
                        MultiImageSelector.create()
                                .showCamera(true)
                                .count(9)
                                .multi()
                                .origin(processPicturePhat)
                                .start(IssuerClassroomActivity.this, REQUEST_CODE + 1);
                    } else {

                        if (processPicturePhat.size() > 9) {
                            processPicturePhat.remove(processPicturePhat.size() - 1);
                        }
                        PhotoActivity.startUI(IssuerClassroomActivity.this, processPicturePhat, holder.getmPosition());
                    }
                }
            });

            holder.setOnClickListener(R.id.item_photo_selectDelete, new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    processPicturePhat.remove(holder.getmPosition());
                    notifyDataSetChanged();
                }
            });
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //获取海报路径
        if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
            haiBaoPath = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT).get(0);
            GlideUtils.show(haiBao, haiBaoPath);
        }
        //过程图片路径
        if (requestCode == REQUEST_CODE + 1 && resultCode == RESULT_OK) {
            processPicturePhat.clear();
            processPicturePhat.addAll(data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT));
            processPicturePhat.add("");
            adapter.notifyDataSetChanged();
        }

        //获取音频路径
        if (requestCode == REQUEST_CODE + 2 && resultCode == RESULT_OK) {
            musicPlayPath = FileUtils.getFileSelectPath(data);
            if (!MediaFile.JudgeFileType(musicPlayPath, "mp3")) {
                ToastUtils.getToastShort("请选择MP3,WMA格式的音频文件");
                return;
            }
            musicPlay.setFilePath(musicPlayPath);
            musicPlay.setVisibility(View.VISIBLE);
        }
        //获取视频路径
        if (requestCode == REQUEST_CODE + 3 && resultCode == RESULT_OK) {
            videoPlayPath = FileUtils.getFileSelectPath(data);
            if (!MediaFile.JudgeFileType(videoPlayPath, "mp4")) {
                ToastUtils.getToastShort("请选择MP4格式的视频文件");
                return;
            }
            videoPlay.setUpDefault(videoPlayPath, "本地视频");
            videoPlay.setThumbRes(R.mipmap.logo);
            videoPlay.setVisibility(View.VISIBLE);

        }


        //录制视频路径
        if (requestCode == REQUEST_CODE + 4 && resultCode == RESULT_OK) {
            videoPlayPath = data.getStringExtra(VideoCameraActivity.RESULT);
            videoPlay.setUpDefault(videoPlayPath, "录制视频");
            videoPlay.setThumbRes(R.mipmap.logo);
            videoPlay.setVisibility(View.VISIBLE);
        }

        //录制音频路径
        if (requestCode == REQUEST_CODE + 5 && resultCode == RESULT_OK) {
            musicPlayPath = data.getStringExtra(RecordActivity.MP3PATH);
            musicPlay.setFilePath(musicPlayPath);
            musicPlay.setVisibility(View.VISIBLE);
        }
    }


    @Override
    protected void onPause() {
        super.onPause();
        if (musicPlay != null) {
            musicPlay.pause();

        }
        if (videoPlay != null) {
            videoPlay.pause();
        }


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (musicPlay != null) {
            musicPlay.release();
        }

        if (viewRoot != null) {
            videoPlay.release();
        }


    }


    private Calendar startTime;
    private Calendar endTime;

    @OnClick({R.id.selectHaiBao, R.id.commit, R.id.selectAudio, R.id.selectVideo, R.id.ll_startTiem, R.id.ll_endTiem})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.selectHaiBao:
                MultiImageSelector.create()
                        .showCamera(true)
                        .single()
                        .start(this, REQUEST_CODE);
                break;
            case R.id.commit:
                if (editHelper.check()) {
                    if (TextUtils.isEmpty(haiBaoPath)) {
                        SnackbarUtil.showShort(this, "海报不能为空", SnackbarUtil.Warning).show();
                        return;
                    }
                    /**
                     * 上传课堂
                     * address:开课地址
                     * begin_time:开课时间，格式为yyyy-MM-dd HH:mm:ss
                     * end_time:截止时间，格式为yyyy-MM-dd HH:mm:ss
                     * price:价格，免费的为0
                     * remark:课堂简介
                     * title:标题
                     * type:课堂形式，1为线下课堂，2为视频课堂
                     * studentNum:招生人数
                     * img_url:组图片，只有一张
                     * img_guocheng:视频
                     * content_img:图片
                     * AudioUrl:音频文件
                     *
                     * @return
                     */
                    if (xianXiaKeTang.isChecked()) {

                        if (TextUtils.isEmpty(address.getEditText().getText().toString())) {
                            SnackbarUtil.showShort(this, "授课地址不能为空", SnackbarUtil.Warning).show();
                            return;
                        }
                        presenter.getHttpData(
                                address.getEditText().getText().toString(),
                                startTiem.getText().toString(),
                                endTiem.getText().toString(),
                                editHelper.getText(R.id.inputPrice),
                                editHelper.getText(R.id.classroomBrief),
                                editHelper.getText(R.id.classroomName),
                                String.valueOf(1),
                                editHelper.getText(R.id.student),
                                haiBaoPath,
                                videoPlayPath,
                                processPicturePhat,
                                musicPlayPath

                        );

                    } else {
                        presenter.getHttpData(
                                "",//线上课堂授课地点为空
                                startTiem.getText().toString(),
                                endTiem.getText().toString(),
                                editHelper.getText(R.id.inputPrice),
                                editHelper.getText(R.id.classroomBrief),
                                editHelper.getText(R.id.classroomName),
                                String.valueOf(2),
                                editHelper.getText(R.id.student),
                                haiBaoPath,
                                videoPlayPath,
                                processPicturePhat,
                                musicPlayPath
                        );
                    }

                    /**
                     * //上传开放式秘籍
                     * type:类型，1为开放式，2为买断式
                     * title:秘籍名称
                     * tedian:特点
                     * maidiantese:卖点特色
                     * price:价格，免费的传0
                     * cuisines_id:菜系，这个在效果图上没有体现出来，需要加上去的
                     * img_url:主图，秘籍效果图，一张">url:主图，秘籍效果图，一张
                     * shipin:视频，可选
                     * <p>
                     * 开放式需要传的参数:
                     * zhuliao:主料，格式为:（名称:数量|名称:数量）
                     * fuliao:辅料，格式为:（名称:数量|名称:数量）
                     * gongyiliucheng:工艺流程
                     * zhuyishixiang:注意事项
                     * img_guocheng:过程图片，可为多张
                     * AudioUrl:音频文件
                     */
//
                }

                break;
            case R.id.selectAudio:
                final DialogSelectMode dialog = new DialogSelectMode(IssuerClassroomActivity.this, "录音", "选择音频");
                dialog.show();
                dialog.setClickCallback(new DialogSelectMode.OnClickCallback() {
                    @Override
                    public void onClick(int type) {
                        if (type == 1) {
                            RecordActivity.startUi(IssuerClassroomActivity.this, REQUEST_CODE + 5, MyApplication.appSDFilePath);
                            dialog.dismiss();
                        } else if (type == 2) {
                            UiUtils.startFileSelect(IssuerClassroomActivity.this, "audio/*", REQUEST_CODE + 2);
                            dialog.dismiss();
                        } else if (type == 0) {
                            dialog.dismiss();
                        }
                    }
                });
                break;
            case R.id.selectVideo:
                final DialogSelectMode dialog2 = new DialogSelectMode(IssuerClassroomActivity.this, "录制", "选择视频");
                dialog2.show();
                dialog2.setClickCallback(new DialogSelectMode.OnClickCallback() {
                    @Override
                    public void onClick(int type) {
                        if (type == 1) {
                            VideoCameraActivity.startActivity(IssuerClassroomActivity.this, MyApplication.appSDFilePath, IssuerClassroomActivity.this.REQUEST_CODE + 4);
                            dialog2.dismiss();
                        } else if (type == 2) {
                            UiUtils.startFileSelect(IssuerClassroomActivity.this, "video/*", REQUEST_CODE + 3);
                            dialog2.dismiss();
                        } else if (type == 0) {
                            dialog2.dismiss();
                        }
                    }
                });
                break;

            case R.id.ll_startTiem:
                DialogDateTime dialogDateTime = new DialogDateTime(this, DialogDateTime.MODE.DATE_Y_M_D);
                dialogDateTime.setTitleMain("开始日期");
                final Calendar calendar = Calendar.getInstance();
                calendar.add(Calendar.YEAR, 1);
                if (endTime != null) {
                    dialogDateTime.setMaxCalendar(endTime);
                } else {
                    dialogDateTime.setMaxCalendar(calendar);
                }

                Calendar calendar2 = Calendar.getInstance();
                dialogDateTime.setMinCalendar(calendar2);
                dialogDateTime.show();
                dialogDateTime.setOnClickCallback(new DialogDateTime.OnClickCallback() {
                    @Override
                    public void onClick(DialogDateTime dialog, int number, Calendar content) {
                        startTime = content;
                        startTiem.setText(content.get(Calendar.YEAR) + "-" + (content.get(Calendar.MONTH) + 1) + "-" + content.get(Calendar.DAY_OF_MONTH));
                    }
                });

                break;


            case R.id.ll_endTiem:
                DialogDateTime dialogDateTime2 = new DialogDateTime(this, DialogDateTime.MODE.DATE_Y_M_D);
                if (startTime == null) {
                    SnackbarUtil.showShort(this, "请先选择开始时间", SnackbarUtil.Info).show();
                    return;
                }
                dialogDateTime2.setTitleMain("结束日期");


                dialogDateTime2.setMinCalendar(startTime);

                dialogDateTime2.show();
                dialogDateTime2.setOnClickCallback(new DialogDateTime.OnClickCallback() {
                    @Override
                    public void onClick(DialogDateTime dialog, int number, Calendar content) {
                        endTime = content;
                        endTiem.setText(content.get(Calendar.YEAR) + "-" + (content.get(Calendar.MONTH) + 1) + "-" + content.get(Calendar.DAY_OF_MONTH));
                    }
                });


                break;


        }
    }


    @Override
    public void upLoading(boolean whetherSucceed) {

    }

    DialogProgress dialogProgress;
    @Override
    public void upLoading(int progress, boolean done, boolean isUpdate, boolean isCompress) {
        if (dialogProgress == null) {
            dialogProgress = new DialogProgress(this);
        }
        dialogProgress.setTitleText("上传中");
        dialogProgress.setProgress(progress);
        dialogProgress.show();
    }

    @Override
    public void dismissProgressDialog() {
        if (dialogProgress != null && dialogProgress.isShowing()) {
            dialogProgress.dismiss();
        }
    }


    @Override
    public void onChange(AnimCheckBox checkBox, boolean checked) {
        if (checkBox.getId() == xianXiaKeTang.getId()) {
            xianXiaKeTang.setChecked(true);
            zaiXiaKeTang.setChecked(false);
            ll_address.setVisibility(View.VISIBLE);
        } else {
            xianXiaKeTang.setChecked(false);
            zaiXiaKeTang.setChecked(true);
            ll_address.setVisibility(View.GONE);
        }

    }
}
